Error Handling in JavaScript

JavaScript provides multiple ways to handle errors, allowing developers to manage exceptions effectively and maintain code stability. Below are common approaches to error handling:

1. Try-Catch Block

The try-catch block is used to catch exceptions and handle errors gracefully.


try {
    let result = 10 / 0;
    console.log(result); // Output: Infinity
    throw new Error("Custom Error Message");
} catch (error) {
    console.error("Error caught:", error.message);
} finally {
    console.log("Execution continues...");
}
    

Output: Error caught: Custom Error Message Execution continues...

2. Using Throw

The throw statement is used to manually throw exceptions.


function divide(a, b) {
    if (b === 0) {
        throw new Error("Cannot divide by zero");
    }
    return a / b;
}

try {
    console.log(divide(10, 0));
} catch (error) {
    console.error(error.message);
}
    

Output: Cannot divide by zero

3. Error Object

The Error object provides additional information about errors.


try {
    JSON.parse("{ invalid JSON }");
} catch (error) {
    console.error("Error Name:", error.name); // SyntaxError
    console.error("Error Message:", error.message); // Unexpected token i in JSON
}
    

Output: Error Name: SyntaxError Error Message: Unexpected token i in JSON

4. Promises with .catch

Promises handle asynchronous errors using the .catch method.


const fetchData = new Promise((resolve, reject) => {
    setTimeout(() => reject("Data fetch failed"), 1000);
});

fetchData
    .then(data => console.log(data))
    .catch(error => console.error("Error:", error));
    

Output (after 1 second): Error: Data fetch failed

5. Async/Await with Try-Catch

When using async/await, errors are caught using a try-catch block.


async function fetchData() {
    try {
        let response = await Promise.reject("Data fetch failed");
        console.log(response);
    } catch (error) {
        console.error("Error:", error);
    }
}

fetchData();
    

Output: Error: Data fetch failed

Conclusion

Proper error handling ensures that your application is resilient and provides meaningful feedback during failures. Combining techniques like try-catch and Promise error handling can significantly enhance code reliability.